package data;

import java.io.Serializable;

import data.Data.*;

public class PlayerType implements Serializable {
	public Race m_race;
	public Role m_role;
	
	public PlayerType( Race race, Role role )
	{
		m_race = race;
		m_role = role;
	}
	
	public boolean equals(Object o)
	{
		if( this == o )
			return true;
		
		if( !(o instanceof PlayerType) )
			return false;
		
		PlayerType other = (PlayerType) o;
		
		return (m_race.equals(other.m_race) && m_role.equals(other.m_role));
	}
	
	public int hashCode()
	{
		int hash = 17;
		hash = 37 * hash + m_race.hashCode();
		hash = 37 * hash + m_race.hashCode();
		
		return hash;
	}
	
	/**
	 * Encodes a PlayerType object as an integer.
	 * @return Returns an integer representing the PlayerType.
	 */
	public int code()
	{
		return 10 * m_race.value() + m_role.value(); 
	}
	
	/**
	 * Decodes a code an creates a new PlayerType object
	 * @param code - the code to decode. Note that the code should only refer to the Race and Role!
	 * @return Returns a PlayerType object
	 * @throws Exception 
	 */
	public static PlayerType decode(int code) throws Exception
	{
		Role role = Role.UNKNOWN;
		Race race = Race.UNKNOWN;
		
		// keep a copy of the original code
		int origCode = code;
		
		int r = code % 10;
		if( r != Role.BLITZER.value() && 
			r != Role.BLOCKER.value() &&
			r != Role.CATCHER.value() &&
			r != Role.LINEMAN.value() &&
			r != Role.THROWER.value() )
			throw new Exception("PlayerType.decode: Bad role code: " + origCode);
		
		if(r == Role.BLITZER.value())
			role = Role.BLITZER;
		if(r == Role.BLOCKER.value())
			role = Role.BLOCKER;
		if(r == Role.CATCHER.value())
			role = Role.CATCHER;
		if(r == Role.LINEMAN.value())
			role = Role.LINEMAN;
		if(r == Role.THROWER.value())
			role = Role.THROWER;
		code = code / 10;
		
		r = code % 10;
		
		if( r != Race.HUMAN.value() &&
			r != Race.ORC.value() && 
			r != Race.ELF.value() )
			throw new Exception("PlayerType.decode: Bad race code: " + origCode);
		
		if(r == Race.HUMAN.value())
			race = Race.HUMAN;
		if(r == Race.ORC.value())
			race = Race.ORC;
		if(r == Race.ELF.value())
			race = Race.ELF;
		
		return new PlayerType(race, role);
	}
}
